package com.eleven.mall.service.impl;

import com.eleven.mall.customexception.BusinessException;
import com.eleven.mall.customexception.SystemException;
import com.eleven.mall.mapper.ManagerMapper;
import com.eleven.mall.mapper.RoleMapper;
import com.eleven.mall.pojo.ExType;
import com.eleven.mall.pojo.ManagerOut;
import com.eleven.mall.pojo.ManagerPage;
import com.eleven.mall.pojo.entity.Manager;
import com.eleven.mall.pojo.entity.ManagerExample;
import com.eleven.mall.pojo.entity.Role;
import com.eleven.mall.service.ManagerService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: Rui_simple
 * @Date: 2022/10/24 19:56
 * @Description: ManagerServiceImpl
 * @Version 1.0.0
 */
@Service
@AllArgsConstructor
public class ManagerServiceImpl implements ManagerService {

    ManagerMapper managerMapper;
    RoleMapper roleMapper;

    /**
     * 获取用户列表
     * 1、查询用户列表信息
     * 2、列表为空抛异常
     * 3、添加分页
     * 4、遍历用户列表并将数组存到ManagerOut集合中作为响应的用户列表数据
     * 5、根据 role_id 得到 role_name
     * 6、将要返回给控制层的数据存储到 managerPage
     * @param query
     * @param pagenum
     * @param pagesize
     * @return
     */
    @Override
    public ManagerPage getUserList(String query, Integer pagenum, Integer pagesize) {
        ManagerPage managerPage = new ManagerPage();
        ManagerExample managerExample = new ManagerExample();
        //managerExample.createCriteria().andMgNameEqualTo(query);
        PageHelper.startPage(pagenum, pagesize);
        //List<Manager> managerList = managerMapper.selectByExample(managerExample);
        List<Manager> managerList = managerMapper.getManagerList(query);
        if (managerList == null || managerList.isEmpty()){
            throw new BusinessException("managerList not found", ExType.BussRecordNotFound);
        }

        ArrayList<ManagerOut> managerOuts = new ArrayList<>();
        //4、遍历 managerList 存到managerOuts集合中作为响应的用户列表数据
        for(Manager m : managerList) {
            ManagerOut manager = new ManagerOut();
            manager.setId(m.getMgId());
            manager.setUsername(m.getMgName());
            manager.setMobile(m.getMgMobile());
            manager.setEmail(m.getMgEmail());
            manager.setRole_name(getRoleNameById(m.getRoleId()));
            //1:false, 0:true
            if (m.getMgState()==1){
                manager.setMg_state(false);
            }else{
                manager.setMg_state(true);
            }
            //manager.setMg_state(m.getMgState());
            managerOuts.add(manager);
        }

        //6、将要返回给控制层的数据存储到 managerPage
        PageInfo<Manager> pageInfo = new PageInfo<>(managerList);
        managerPage.setTotal((int) pageInfo.getTotal());
        managerPage.setPagenum(pageInfo.getPageNum());
        managerPage.setUsers(managerOuts);

        return managerPage;
    }
    //5、根据 role_id 得到 role_name
    private String getRoleNameById(Short id){
        //System.out.println(id);
        Role role = roleMapper.selectByPrimaryKey(id);
        if (role == null){
            throw new BusinessException("role not found", ExType.BussRecordNotFound);
        }
        //System.out.println(role.getRoleName());
        return role.getRoleName();
    }


    /**
     * 添加用户
     * 1、得到用户名、密码、邮箱、手机号
     * 2、密码进行md5加密，判断用户名是否重复
     * 3、将新的用户信息提那家到数据库
     * 4、判断是否添加成功，受影响行数不唯一抛异常
     * 5、添加成功,查询用户信息，返回 managerout 对象
     * @param manager
     * @return
     */
    @Override
    public Manager addUser(Manager manager) {
        String password = DigestUtils.md5DigestAsHex(manager.getMgPwd().getBytes());
        manager.setMgPwd(password);
        manager.setRoleId((short) 40);
        manager.setMgTime(0);
        manager.setMgState((byte)1);
        int flag = managerMapper.insert(manager);
        if (flag != 1) {
            throw new SystemException("insert user fail",ExType.SystemInsertFail);
        }

        ManagerExample managerExample = new ManagerExample();
        managerExample.createCriteria().andMgNameEqualTo(manager.getMgName());
        List<Manager> managerList = managerMapper.selectByExample(managerExample);
        Manager managerout = managerList.get(0);
        //System.out.println(managerList.get(0));
        return managerout;
    }

    /**
     * 修改用户状态：
     * 1、根据用户id修改用户状态
     * 2、判断受影响行数是否为1 ，不为1抛异常
     * 3、为1 修改成功
     * @param id
     * @param type
     * @return
     */
    @Override
    public Manager changeUserType(Integer id, Boolean type) {
        ManagerExample managerExample = new ManagerExample();
        Manager manager = new Manager();
        manager.setMgId(id);
        //1:false, 0:true
        if (type == true){
            manager.setMgState((byte)0);
        }else if (type == false){
            manager.setMgState((byte)1);
        }
        //manager.setMgState(type);
        //managerExample.createCriteria()
        int flag = managerMapper.updateByPrimaryKeySelective(manager);
        if (flag != 1) {
            throw new SystemException("change user type fail",ExType.SystemUpdateFail);
        }
        return manager;
    }

    /**
     * 根据用户id获取用户信息
     * @param id
     * @return
     */
    @Override
    public Manager getUserById(Integer id) {
        Manager manager = managerMapper.selectByPrimaryKey(id);
        return manager;
    }

    /**
     * 修改用户信息
     * 1、根据用户id修改对应用户信息
     * 2、判断受影响行数不唯一抛异常
     * @param id
     * @param manager
     * @return
     */
    @Override
    public Manager changeUser(Integer id, Manager manager) {
        int flag = managerMapper.updateByPrimaryKeySelective(manager);
        if (flag != 1) {
            throw new SystemException("change user fail",ExType.SystemUpdateFail);
        }
        return manager;
    }

    /**
     * 删除用户：
     * 1、根据id删除用户
     * @param id
     * @return
     */
    @Override
    public Boolean deleteUser(Integer id) {
        int flag = managerMapper.deleteByPrimaryKey(id);
        if (flag != 1) {
            return false;
        }
        return true;
    }

    /**
     * 分配用户角色
     * @param id
     * @param manager
     * @return
     */
    @Override
    public Manager changeUserRole(Integer id, Manager manager) {
        manager.setMgId(id);
        int flag = managerMapper.updateByPrimaryKeySelective(manager);
        if (flag != 1) {
            throw new SystemException("change user role fail",ExType.SystemUpdateFail);
        }
        return manager;
    }


}
